import UIKit
import SnapKit

class InputRowCell: UITableViewCell {
    static let reuseId = "InputRowCell"

    let cardView = UIView()
    let indexLab = UILabel()
    let textField = UITextField()

    var onTextChange: ((String) -> Void)?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setup()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }

    private func setup() {
        backgroundColor = .white
        self.contentView.addSubview(cardView)
        cardView.backgroundColor = Colors.blue.withAlphaComponent(0.1)
        cardView.addSubview(indexLab)
        cardView.addSubview(textField)

        indexLab.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        indexLab.textColor = Colors.blue
        indexLab.textAlignment = .center
        indexLab.layer.cornerRadius = 12.5
        indexLab.layer.masksToBounds = true
        indexLab.borderSet(Colors.blue, 0.5)

        //
        textField.font = UIFont.systemFont(ofSize: 18)
        textField.placeholder = "请输入"
        textField.clearButtonMode = .whileEditing
        textField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)

    }

    func configure(index: Int, text: String) {
        indexLab.text = "\(index)"
        textField.text = text
    }

    @objc private func textChanged(_ tf: UITextField) {
        onTextChange?(tf.text ?? "")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        cardView.frame = CGRect(x: 10, y: 5, width: self.width-20, height: self.height-10)
        cardView.circular()
        indexLab.frame = CGRect(x: 10, y: (cardView.height-25)*0.5, width: 25, height: 25)
        textField.frame = CGRect(x: indexLab.frame.maxX+10, y: 0, width: cardView.width-indexLab.frame.maxX-30, height: cardView.height)
    }
}
